package com.fenxiao.user.action;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;
import java.util.Set;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.io.FileUtils;

import net.sf.json.JSONObject;

import org.apache.struts2.ServletActionContext;

import com.cloopen.rest.sdk.CCPRestSDK;
import com.cloopen.rest.sdk.utils.encoder.BASE64Encoder;
import com.fenxiao.card.entity.Bankcard;
import com.fenxiao.card.service.CardService;
import com.fenxiao.agent.entity.Agent;
import com.fenxiao.agent.service.AgentService;
import com.fenxiao.common.Pager;
import com.fenxiao.pay.entity.PayRecord;
import com.fenxiao.pay.service.PayRecordService;
import com.fenxiao.present.entity.PresentRecord;
import com.fenxiao.present.service.PresentService;
import com.fenxiao.task.action.TaskAction;
import com.fenxiao.task.entity.Task;
import com.fenxiao.task.entity.cishu;
import com.fenxiao.task.service.CishuService;
import com.fenxiao.task.service.TaskService;
import com.fenxiao.user.entity.User;
import com.fenxiao.user.service.UserService;
import com.fenxiao.util.Tools;
import com.opensymphony.xwork2.ActionSupport;
import com.weixin.po.AccessToken;
import com.weixin.servlet.WeixinServlet;
import com.weixin.utils.MessageUtil;
import com.weixin.utils.QRCodeUtil;
import com.weixin.utils.Utils;
import com.weixin.utils.WeixinUtil;
import com.weixin.utils.wexinxingxi;

public class UserAction extends ActionSupport {

	private HttpServletRequest request;
	private HttpServletResponse response;
	private HttpSession session;
	private CishuService  cishuService;

	public CishuService getCishuService() {
		return cishuService;
	}
	public void setCishuService(CishuService cishuService) {
		this.cishuService = cishuService;
	}

	private Map<String, Object> dataMap;

	private String msg; // 错误提示
	private String num;

	private User user;
	private UserService userService;
	private AgentService agentService;
	private Agent agent;

	private int page=1;
	private Pager pageBean;
	private List<User> userList;
	private String search;
	private long agentId;
	private String userPassword;

	private File fileTest; // 接收这个上传的文件
	private String fileTestFileName;
	private File fileTest1; // 接收这个上传的文件
	private String fileTest1FileName;

	private PresentService presentService;
	private String openId;
	private TaskService taskService;

	private CardService cardService;

	// 登陆
	public String userLogin() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		user = userService.checkUserLogin(user);
		if (user != null) {
			session.setAttribute("user", user.getId());
		} else {
			msg = "账号或密码错误!";
			request.setAttribute("msg", msg);
			return "loginError";
		}
		return "loginSuccess";

	}
	// 退出
	public String userOuot() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		Cookie cookie = new Cookie("userid", null);  
		response.addCookie(cookie);  
		session.invalidate();
		return "forgetPasswordForLogin";
		
	}
//提现
	public String moneyToCash() throws Exception {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		long userId = user.getId();

		Bankcard bankcard1 = cardService.queryBankcardOfUser(userId);
		String password = bankcard1.getCardPassword();
		String amount = request.getParameter("amount");
		double amount1 = Double.parseDouble(amount);

		User user2 = userService.queryuserById(userId);
		PresentRecord presentRecord = new PresentRecord();
		presentRecord.setUser(user2);
		if(user2.getBalance()>1){
		double shouxu = (amount1 * 0.006);
		NumberFormat formatter1 = new DecimalFormat("#0.00");
		double shoux = Double.parseDouble(formatter1.format(shouxu));//（四舍五入）     
		double nalance = (amount1+shoux);
		NumberFormat formatter = new DecimalFormat("#0.00");
		String nana = formatter.format(nalance);//（四舍五入）
		double xiaoshu = Double.parseDouble(nana);
		double zhongshu = (user2.getBalance()-xiaoshu);
		NumberFormat zhongs = new DecimalFormat("#0.00");
		double zs = Double.parseDouble(formatter.format(zhongshu));//（四舍五入
		presentRecord.setRemainingSum(zs);
		presentRecord.setPresentMoney(amount1);
		presentRecord.setPresentFee(shoux);
		Date date = new Date();
		SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String str = format.format(date);
		presentRecord.setPresentTime(str);
		openId = user.getWeChatId();
		request.setAttribute("openId", openId);
		     String presen = user.getPresentPass();
		    	 if(password!=null&&!"".equals(presen)&&presen!=null&&password.equals(presen)||password!=null&&!"".equals(presen)&&presen!=null&&password.equals(EncoderByMd5(presen))){
		    presentService.addPresentRecord(presentRecord);
				userService.updateBalanceOfUser(zs, userId);
				User user3 = userService.queryuserById(userId);
			request.setAttribute("user",user3);
			return myPersonal();
		    	  }else {
//		    		  HttpServletResponse response = ServletActionContext.getResponse();
//		    		  response.setContentType("text/html;charset=UTF-8");
//		    		  response.setCharacterEncoding("UTF-8");//防止弹出的信息出现乱码
//		    		  PrintWriter out = null;
//		    		  try {
//		    		      out = response.getWriter();
//		    		      out.print("<script>alert('交易密码错误')</script>");
//		    		      out.print("<script>window.location.href='/index.action'</script>");
//		    		      out.flush();
//		    		      out.close();
//		    		      
//		    		  } catch (IOException e) {
//		    		      e.printStackTrace();
//		    		  }
//		    		  return "moneyes";
		    		  	msg="提现密码错误";
						request.setAttribute("msg",msg );
						request.setAttribute("bankcard", bankcard1);
						return "moneyes";
				}
		}else {
 		  	msg="你的余额不足";
				request.setAttribute("msg",msg );
				request.setAttribute("bankcard", bankcard1);
				return "moneyes";
		}
		   
//		try {	
//			if(!password.equals(user.getPresentPass())){
//				System.err.println("密码错误");
//				msg="提现密码错误";
//				request.setAttribute("msg",msg );
//				return "moneyCashPostal";
//			}else {	
//				presentService.addPresentRecord(presentRecord);
//				userService.updateBalanceOfUser(xiaoshu, userId);
//				return "money";
//			}
//		} catch (Exception e) {
//			e.printStackTrace();
//			msg="提现密码错误";
//		}
	}
	//修改角色信息
	public String Userjuese(){
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		HttpSession session1 = request.getSession();
		Long  user1 = (Long) session1.getAttribute("user");
	user = userService.queryuserById(user1);
	request.setAttribute("user", user);
		return "gerenxinxi";
		
	}

	public String queryUserByOpenId() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		String openId = request.getParameter("openId");
		User user = userService.queryMoneyOfUser(openId);
		request.setAttribute("user", user);

		return "register";
	}

	// 关闭
	public String guangbi() throws Exception {

		long id = user.getId();
		User userid = userService.queryuserById(id);
		userid.setUserStatus(user.getUserStatus());
		userService.updateUser(userid);
		if(userid.getUserLevel() == 3){
			agentId = userid.getAgentsId();
			
			return queryUserList();
		}
		return queryAllUserList();

	}
	//MD5
	public String EncoderByMd5(String str) throws Exception{
        //确定计算方法
        MessageDigest md5=MessageDigest.getInstance("MD5");
        BASE64Encoder base64en = new BASE64Encoder();
        //加密后的字符串
        String newstr=base64en.encode(md5.digest(str.getBytes("utf-8")));
        return newstr;
    }
	// 注册
	public String register() throws Exception {
		System.err.println("注册成功------------------");
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		
		String code = request.getParameter("code");
		String recomCode = request.getParameter("recomCode");
		String openId1 = request.getParameter("WeChatId");
		User user2 = userService.queryMoneyOfUser(openId1);
		if (user2 == null) {
		 List<User> list = userService.queryUserList();
			String recomCode1=userService.getRecommendCode();
			String resut = URLEncoder.encode("http://wxad.vipshequ.com/FenXiao/UserAction_registname");
//			String resut = URLEncoder.encode("http://czw.tunnel.qydev.com/FenXiao/UserAction_registname");
//			String thisa = "E:/JAVAtomecat/apache-tomcat-7.0.57/webapps/FenXiao/uploads";
//			String text = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe7ec609a80419e1e&redirect_uri="+resut+"?recomCode="
			String thisa = "/web/adfenxiao/FenXiao/uploads";
			String text = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9d49f59517209fb7&redirect_uri=http://wxad.vipshequ.com/FenXiao/UserAction_registname?recomCode="
					+ recomCode1
					+ "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
			String fileName = QRCodeUtil.encode(text, null, thisa, true);
			User user1 = new User();
			         cishu cishu = new cishu();
			         cishu cishu1 = cishuService.queryAll();
			         Integer zhuche = cishu1.getZhuche();
			          if(zhuche!=0&&zhuche!=null){
			        	  cishu1.setZhuche(zhuche+1);
			          }else{
			        	  cishu1.setZhuche(1);
			          }
			          cishuService.updatecishu(cishu1);
			// 代理商
			String agentsId = request.getParameter("agentsId");
			if(agentsId!=null&&!"".equals(agentsId)){
				long agents = Long.parseLong(agentsId);
			     Agent agentUser = agentService.queryHehuo(agents);
			     if(agentUser!=null){
			     Long partner = agentUser.getPartnerId();
			     if(partner!=null){
			    	 user1.setPartnerId(partner);
			     }
			     user1.setUserLevel(3);
			     user1.setAgentsId(agents);
			  }
				
			}else {
				  User user3 = userService.queryUserSadff(recomCode);
				if(user3!=null){

						user1.setPartnerId(user3.getPartnerId());
						user1.setAgentsId(user3.getAgentsId());
						if(user3.getUserLevel()==3){		
							user1.setSadffId(user3.getId());
						}else {
							if(user3.getSadffId()!=null){							
								user1.setSadffId(user3.getSadffId());
							}
						}
					}
				user1.setUserLevel(1);
			}
			String mobile = request.getParameter("mobile");
			String province = request.getParameter("province");
			String city = request.getParameter("city");
			String area = request.getParameter("area");
			String Username = request.getParameter("userName");
			String userPassword = request.getParameter("userPassword");
			String WeChatId = request.getParameter("WeChatId");
			String sex1 = request.getParameter("sex");
			if(sex1!=null&&!"".equals(sex1)){
				Integer sex = Integer.parseInt(sex1);
				user1.setSex(sex);
			}
			String nickName = request.getParameter("nickName");	
				user1.setNickName(nickName);
			String userPhoto = request.getParameter("userPhoto");
				user1.setUserPhoto(userPhoto);
			user1.setMobile(mobile);
			
			if (province.equals("省")) {
				user1.setProvince("全国");
			} else {
				user1.setProvince(province);
			}
			if (city.equals("市")) {
				user1.setCity("全国");
			} else {
				user1.setCity(city);
			}
			if (area.equals("区")) {
				user1.setArea("全国");
			} else {
				user1.setArea(area);
			}
			Date date = new Date();
			SimpleDateFormat formatter = new SimpleDateFormat(
					"yyyy-MM-dd HH:mm:ss");
			String dateString = formatter.format(date);
			user1.setRegTime(dateString);
			user1.setUsername(Username);
			user1.setUserPassword(EncoderByMd5(userPassword));
			user1.setWeChatId(WeChatId);
			user1.setRecomCode(recomCode);
			user1.setRecommendationCode(recomCode1);
			user1.setUserQr("/uploads/" + fileName);
			user1.setUserStatus(1);
			user1.setSubscribe(1);

			userService.addUser(user1);
			return "myQRCode";
		} else {
			msg = "账号已存在，请登录";
			return "register";
		}

	}

	// 扫描二维码 跳转页面
	public String registname() throws freemarker.core.ParseException, IOException {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();

		// 代理商
		String agentsId = request.getParameter("agentsId");
		if(agentsId!=null){
			   long agents = Long.parseLong(agentsId);
			   Agent agentUser = agentService.queryHehuo(agents);
			   if(agentUser!=null){
				 String recomCode = agentUser.getRecommendationCode();
				 request.setAttribute("recomCode", recomCode);
				 request.setAttribute("agentsId", agentsId);
			   }
		}else {
			String recomCode = request.getParameter("recomCode");
			request.setAttribute("recomCode", recomCode);
		}
			
		String code = request.getParameter("code");
		// 获取链接微信APP
//		String o_auth_openid_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
//		String requestUrl = o_auth_openid_url
//				.replace("APPID", "wxe7ec609a80419e1e")
//				.replace("SECRET", "c1c8dcb506e7da719047611db642e15d")
//				.replace("CODE", code);
		String o_auth_openid_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
		String requestUrl = o_auth_openid_url
				.replace("APPID", "wx9d49f59517209fb7")
				.replace("SECRET", "8ce29d6424530ba7e803dc4c8146c794")
				.replace("CODE", code);	
		JSONObject jsonObject = Utils.httpsRequest(requestUrl, "GET", null);
		String openId1 = jsonObject.getString("openid");
		String accesstoken = jsonObject.getString("access_token");
		//获取用户个人信息
		String requestUrl1 = "https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID&lang=zh_CN";
		String requestUrl12 = requestUrl1.replace("OPENID", openId1).replace("ACCESS_TOKEN", accesstoken);		
		JSONObject jsonObject2 = Utils.httpsRequest(requestUrl12, "GET", null);
		String sex = jsonObject2.getString("sex");
		String nickName = jsonObject2.getString("nickname");
		String userPhoto = jsonObject2.getString("headimgurl");
		request.setAttribute("sex", sex);
		request.setAttribute("nickName", nickName);
		request.setAttribute("userPhoto", userPhoto);
		request.setAttribute("openId", openId1);
		User user2 = userService.queryMoneyOfUser(openId1);
		if (user2 == null) {
			return "registname";
		} else {
			msg = "账号已存在，请登录";
			return "registname";
		}

	}
//进入微信的登录方法
	public String registerAfterSubscribe() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();

		String openId = null;
		String code = request.getParameter("code");
//		String o_auth_openid_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
//		String requestUrl = o_auth_openid_url
//				.replace("APPID", "wxe7ec609a80419e1e")
//				.replace("SECRET", "c1c8dcb506e7da719047611db642e15d")
//				.replace("CODE", code);
		String o_auth_openid_url = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code";
		String requestUrl = o_auth_openid_url
				.replace("APPID", "wx9d49f59517209fb7")
				.replace("SECRET", "8ce29d6424530ba7e803dc4c8146c794")
				.replace("CODE", code);

		openId = (String) request.getSession().getAttribute("openId");
		if (openId == null || openId.equals("")) {
			JSONObject jsonObject = Utils.httpsRequest(requestUrl, "GET", null);
			openId = jsonObject.getString("openid");
		}
		HttpSession session = request.getSession(true);
		session.setAttribute("openId", openId);

		request.setAttribute("openId", openId);
		return "registerAfterSubscribe";
	}

	public String registerAfterSubscribe2() throws Exception {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		String openId = user.getWeChatId();
		User user1 = userService.queryMoneyOfUser(openId);
		User user2 = userService.queryUserSadff(user1.getRecomCode());
		String recomCode1 = null;
		if (user1.getRecommendationCode() == null) {
			recomCode1 = userService.getRecommendCode();
		} else {
			recomCode1 = user1.getRecommendationCode();
		}

//	String thisa = "/web/adfenxiao/FenXiao/uploads";
//		String thisa = "E:/JAVAtomecat/apache-tomcat-7.0.57/webapps/FenXiao/uploads";
//		String text = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe7ec609a80419e1e&redirect_uri=http://czw.tunnel.qydev.com/FenXiao/UserAction_register?recomCode="
//				+ recomCode1
//				+ "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
//		String fileName = QRCodeUtil.encode(text, null, thisa, true);
		String thisa = "/web/adfenxiao/FenXiao/uploads";
//		 String thisa = "/web/adfenxiao/FenXiao/uploads";
		String text = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9d49f59517209fb7&redirect_uri=http://wxad.vipshequ.com/FenXiao/UserAction_register?recomCode="
				+ recomCode1
				+ "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
		String fileName = QRCodeUtil.encode(text, null, thisa, true);
		user1.setUserQr("/uploads/" + fileName);
		user1.setUserLevel(1);
		user1.setUserStatus(1);
		if (user1.getRecommendationCode() == null) {
			user1.setRecommendationCode(recomCode1);
		} else {
			user1.setRecommendationCode(user1.getRecommendationCode());
		}

		if (user.getProvince().equals("省")) {
			user1.setProvince("全国");
		} else {
			user1.setProvince(user.getProvince());
		}
		if (user.getCity().equals("市")) {
			user1.setCity("全国");
		} else {
			user1.setCity(user.getCity());
		}
		if (user.getArea().equals("区")) {
			user1.setArea("全国");
		} else {
			user1.setArea(user.getArea());
		}
		if (user2 != null) {
			if (user2.getUserLevel() == 3) {
				user1.setSadffId(user2.getId());
			} else {
				user1.setSadffId(user2.getSadffId());
			}
			if (user2.getAgentsId() != null) {
				user1.setAgentsId(user2.getAgentsId());
			}
			if (user2.getPartnerId() != null) {
				user1.setPartnerId(user2.getPartnerId());
			}
		}
		userService.updateUser(user1);
		// userService.updateUserAfterSubscribe(user);
		request.setAttribute("openId", user1.getWeChatId());
		return "login2";
	}

	public String forgetPasswordForloginEntering() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		/*
		 * User
		 * user=userService.queryMoneyOfUser(request.getParameter("openId"));
		 * request.setAttribute("user",user);
		 */
		return "forgetPasswordForloginEntering";
	}

	public String forgetPasswordForLogin() throws Exception {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		/*
		 * User
		 * user=userService.queryMoneyOfUser(request.getParameter("openId"));
		 * request.setAttribute("user",user);
		 */
		      User user2 = new User();
		String UserPassword = user.getUserPassword();
		String modil = user.getMobile();
		user2.setUserPassword(EncoderByMd5(UserPassword));
		user2.setMobile(modil);
		userService.updateUserByMobile(user2);
		return "forgetPasswordForLogin";
	}

	public String registerAfterSubscribeCompletion() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		String openId = request.getParameter("openId");
		User user = userService.queryMoneyOfUser(openId);
		if (user != null) {
			request.setAttribute("regTime", user.getRegTime());
			request.setAttribute("user", user);
		}
		request.setAttribute("openId", openId);
		return "registerAfterSubscribeCompletion";
	}
//	//个人信息修改
//	public String gerrenxinxi() throws Exception {
//		request = ServletActionContext.getRequest();
//		response = ServletActionContext.getResponse();
//		 HttpSession session1 = request.getSession();
//		    Long user2 = (Long)session1.getAttribute("user");
//		User user1 = new User();
//		int type = 0;
//		System.err.println("fileTest+-------------"+fileTest);
//		System.err.println("fileTestFileName+-------------"+fileTestFileName);
//		String[] str = { ".jpg", ".jpeg", ".bmp", ".png", ".gif" };
//		// 限定文件大小是4MB
//		if (fileTest != null) {
//			if (fileTest.length() > 2097152) {
//				msg = "图片大小超出了2M";
//				return Userjuese();
//			} else {
//
//				for (String s : str) {
//					if (fileTestFileName.endsWith(s)) {
//						type = 1;
//						String realPath = ServletActionContext
//								.getServletContext().getRealPath("/faceimages");// 实际路径
//						// String realPath ="d:/upload/faceimages";
//						System.out.println(realPath);
//						fileTestFileName = Tools.getRandomFileName() + s;
//						File saveFile = new File(new File(realPath),
//								fileTestFileName); // 在该实际路径下实例化一个文件
//						// 判断父目录是否存在
//						if (!saveFile.getParentFile().exists()) {
//							saveFile.getParentFile().mkdirs();
//						}
//						try {
//							// 执行文件上传
//							// FileUtils 类名 org.apache.commons.io.FileUtils;
//							// 是commons-io包中的，commons-fileupload 必须依赖
//							// commons-io包实现文件上次，实际上就是将一个文件转换成流文件进行读写
//							FileUtils.copyFile(fileTest, saveFile);
//							user.setUserPhoto("faceimages/" + fileTestFileName);
//						} catch (IOException e) {
//							msg = "图片上传失败";
//							return Userjuese();
//						}
//					}
//				}
//				if (type == 0) {
//					msg = "上传的图片类型错误";
//					return Userjuese();
//				}
//			}
//		}
//				user1.setId(user2);
//			userService.updateUsergeren(user1);
//		return myPersonal();
//	}

	public String checkMobile() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		dataMap = new HashMap<String, Object>();
		String mobile = request.getParameter("mobile");
		User user = userService.checkMobile(mobile);
		if (user != null) {
			dataMap.put("code", 0);
		} else {
			dataMap.put("code", 1);
		}
		return "dataMap";
	}

	public String myPersonal() throws Exception {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		Long  userid = (Long) session.getAttribute("user");
		User user1 = userService.queryuserById(userid);
		// String thisa =
		// "D:/Program Files/Java/tomcat8.0.36/webapps/FenXiao/uploads";
		// String text =
		// "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9d49f59517209fb7&redirect_uri=http://czw.tunnel.qydev.com/FenXiao/UserAction_register?recomCode=87837&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
		// String text="http://weixin.qq.com/r/Mzv-57LEse-OrfaE924h";
		// String fileName = QRCodeUtil.encode(text, null, thisa, true);
		/*
		 * request.setAttribute("imageName", fileName);
		 * 
		 * User user=userService.queryMoneyOfUser(openId);
		 * request.setAttribute("user", user);
		 */
		request.setAttribute("user", user1);
//		request.setAttribute("userId", user1);
//		request.setAttribute("openId", openId);
		return "myPersonal";
	}

	/**
	 * 分页查询员工
	 * 
	 * @return
	 */
	public String queryUserList() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		pageBean = userService.queryUserPage(3, page, search, agentId);
		userList = pageBean.getList();
		agent = agentService.queryAgentInfo(agentId);
		request.setAttribute("userList", userList);
		request.setAttribute("agent", agent);
		return "queryUserList";
	}

	/**
	 * 添加员工页面
	 * 
	 * @return
	 */
	public String addStaffPage() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		agent = agentService.queryAgentInfo(agentId);
		request.setAttribute("agent", agent);
		return "addStaffPage";
	}

	/**
	 * 添加员工
	 * 
	 * @return
	 * @throws Exception
	 */
	public String addStaff() throws Exception {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		int type = 0;
		String[] str = { ".jpg", ".jpeg", ".bmp", ".png", ".gif" };
		// 限定文件大小是4MB
		if (fileTest != null) {
			if (fileTest.length() > 2097152) {
				msg = "图片大小超出了2M";
				return addStaffPage();
			} else {

				for (String s : str) {
					if (fileTestFileName.endsWith(s)) {
						type = 1;
						String realPath = ServletActionContext
								.getServletContext().getRealPath("/faceimages");// 实际路径
						// String realPath ="d:/upload/faceimages";
						System.out.println(realPath);
						fileTestFileName = Tools.getRandomFileName() + s;
						File saveFile = new File(new File(realPath),
								fileTestFileName); // 在该实际路径下实例化一个文件
						// 判断父目录是否存在
						if (!saveFile.getParentFile().exists()) {
							saveFile.getParentFile().mkdirs();
						}
						try {
							// 执行文件上传
							// FileUtils 类名 org.apache.commons.io.FileUtils;
							// 是commons-io包中的，commons-fileupload 必须依赖
							// commons-io包实现文件上次，实际上就是将一个文件转换成流文件进行读写
							FileUtils.copyFile(fileTest, saveFile);
							user.setUserPhoto("faceimages/" + fileTestFileName);
						} catch (IOException e) {
							msg = "图片上传失败";
							return addStaffPage();
						}
					}
				}
				if (type == 0) {
					msg = "上传的图片类型错误";
					return addStaffPage();
				}
			}
		}
		if (user.getUserPassword() == null) {
			msg = "密码不能为空！";
			return addStaffPage();
		} else {
			if (!userPassword.trim().equals(user.getUserPassword().trim())) {
				msg = "两次密码输入不一致！";
				return addStaffPage();
			} else {
				user.setUserPassword(userPassword);
			}
		}
		String openId = user.getWeChatId();
		User user1 = userService.queryMoneyOfUser(openId);

		String recomCode1 = null;
		if (user1 != null) {
			if (user1.getRecommendationCode() == null) {
				recomCode1 = userService.getRecommendCode();
			} else {
				recomCode1 = user1.getRecommendationCode();
			}
		} else {
			recomCode1 = userService.getRecommendCode();
		}
		String thisa = "/web/adfenxiao/FenXiao/uploads";
		String text = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wx9d49f59517209fb7&redirect_uri=http://wxad.vipshequ.com/FenXiao/UserAction_register?recomCode="
				+ recomCode1
				+ "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
//		String thisa = "E:/JAVAtomecat/apache-tomcat-7.0.57/webapps/FenXiao/uploads";
//		String text = "https://open.weixin.qq.com/connect/oauth2/authorize?appid=wxe7ec609a80419e1e&redirect_uri=http://czw.tunnel.qydev.com/FenXiao/UserAction_register?recomCode="
//				+ recomCode1
//				+ "&response_type=code&scope=snsapi_userinfo&state=123#wechat_redirect";
		String fileName = QRCodeUtil.encode(text, null, thisa, true);
		user.setUserQr("/uploads/" + fileName);
		
		if (user1 != null) {
			if (user1.getRecommendationCode() == null) {
				user.setRecommendationCode(recomCode1);
			} else {
				user.setRecommendationCode(user1.getRecommendationCode());
			}
		} else {
			user.setRecommendationCode(recomCode1);
		}
		if (user.getProvince().equals("省")) {
			user.setProvince("全国");
		}
		if (user.getCity().equals("市")) {
			user.setCity("全国");
		}
		if (user.getArea().equals("区")) {
			user.setArea("全国");
		}

		agent = agentService.queryAgentInfo(agentId);
		user.setAgentsId(agentId);
		user.setPartnerId(agent.getPartnerId());
		Date date = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(date);
		user.setRegTime(dateString);
		user.setRecommendationCode(showSmsCode() + "");

		int i = userService.addUser(user);

		return queryUserList();
	}

	/**
	 * 批量删除员工
	 * 
	 * @return
	 */
	public String deleteAllStaff() {
		int i = userService.deleteUser(num);
		if (i > 0) {
			msg = "删除成功！";
		} else {
			msg = "删除失败！";
		}
		agentId = agentId;
		return queryUserList();
	}

	/**
	 * 删除员工
	 * 
	 * @return
	 */
	public String deleteStaff() {
		int i = userService.deleteUser1(user.getId());
		if (i > 0) {
			msg = "删除成功！";
		} else {
			msg = "删除失败！";
		}
		agentId = agentId;
		return queryUserList();
	}

	/**
	 * 修改员工页面
	 * 
	 * @return
	 */
	public String updateStaffPage() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		agent = agentService.queryAgentInfo(agentId);
		user = userService.queryUserInfo(user);
		request.setAttribute("user", user);
		request.setAttribute("agent", agent);
		return "updateStaffPage";
	}

	/**
	 * 修改员工
	 * 
	 * @return
	 * @throws Exception 
	 */
	
	  public String updateStaff() throws Exception{
		  User u =  userService.queryUserInfo(user);
		  request = ServletActionContext.getRequest();
			response = ServletActionContext.getResponse();
			HttpSession session = request.getSession();
			int type = 0;
			String[] str = { ".jpg", ".jpeg", ".bmp", ".png", ".gif" };
			// 限定文件大小是4MB
			if (fileTest != null) {
				if (fileTest.length() > 2097152) {
					msg = "图片大小超出了2M";
					return updateStaffPage();
				} else {

					for (String s : str) {
						if (fileTestFileName.endsWith(s)) {
							type = 1;
							String realPath = ServletActionContext
									.getServletContext().getRealPath("/faceimages");// 实际路径
							// String realPath ="d:/upload/faceimages";
							System.out.println(realPath);
							fileTestFileName = Tools.getRandomFileName() + s;
							File saveFile = new File(new File(realPath),
									fileTestFileName); // 在该实际路径下实例化一个文件
							// 判断父目录是否存在
							if (!saveFile.getParentFile().exists()) {
								saveFile.getParentFile().mkdirs();
							}
							try {
								// 执行文件上传
								// FileUtils 类名 org.apache.commons.io.FileUtils;
								// 是commons-io包中的，commons-fileupload 必须依赖
								// commons-io包实现文件上次，实际上就是将一个文件转换成流文件进行读写
								FileUtils.copyFile(fileTest, saveFile);
								u.setUserPhoto("faceimages/" + fileTestFileName);
							} catch (IOException e) {
								msg = "图片上传失败";
								return updateStaffPage();
							}
						}
					}
					if (type == 0) {
						msg = "上传的图片类型错误";
						return updateStaffPage();
					}
				}
			}
			if (user.getUserPassword() == null) {
				msg = "密码不能为空！";
				return updateStaffPage();
			} else {
				if (!userPassword.trim().equals(user.getUserPassword().trim())) {
					msg = "两次密码输入不一致！";
					return updateStaffPage();
				} else {
					u.setUserPassword(userPassword);
				}
			}
			
		
			if (user.getProvince().equals("省")) {
				user.setProvince("全国");
			}
			if (user.getCity().equals("市")) {
				user.setCity("全国");
			}
			if (user.getArea().equals("区")) {
				user.setArea("全国");
			}
			u.setProvince(user.getProvince());
			u.setCity(user.getCity());
			u.setArea(user.getArea());
			agent = agentService.queryAgentInfo(agentId);
			u.setAgentsId(agentId);
			u.setPartnerId(agent.getPartnerId());
			u.setUsername(user.getUsername());
			u.setNickName(user.getNickName());
			u.setSex(user.getSex());
			u.setMobile(user.getMobile());
			u.setWeChatId(user.getWeChatId());
			int i = userService.updateUser(u);

			return queryUserList();
	 
	 }
	
	/**
	 * 员工详情
	 * 
	 * @return
	 */
	public String queryStaffInfo() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		user = userService.queryUserInfo(user);
		request.setAttribute("user", user);
		return "queryStaffInfo";
	}

	/**
	 * 查询所有的会员
	 * 
	 * @return
	 */
	public String queryAllUserList() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		pageBean = userService.queryAllUserPage(3, page, search);
		userList = pageBean.getList();
		request.setAttribute("userList", userList);
		return "queryAllUserList";

	}

	/**
	 * 添加会员
	 * 
	 * @return
	 */
	public String addAllUser() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		int type = 0;
		String[] str = { ".jpg", ".jpeg", ".bmp", ".png", ".gif" };
		// 限定文件大小是4MB
		if (fileTest != null) {
			if (fileTest.length() > 2097152) {
				msg = "图片大小超出了2M";
				return "imgErro";
			} else {

				for (String s : str) {
					if (fileTestFileName.endsWith(s)) {
						type = 1;
						String realPath = ServletActionContext
								.getServletContext().getRealPath("/faceimages");// 实际路径
						// String realPath ="d:/upload/faceimages";
						System.out.println(realPath);
						fileTestFileName = Tools.getRandomFileName() + s;
						File saveFile = new File(new File(realPath),
								fileTestFileName); // 在该实际路径下实例化一个文件
						// 判断父目录是否存在
						if (!saveFile.getParentFile().exists()) {
							saveFile.getParentFile().mkdirs();
						}
						try {
							// 执行文件上传
							// FileUtils 类名 org.apache.commons.io.FileUtils;
							// 是commons-io包中的，commons-fileupload 必须依赖
							// commons-io包实现文件上次，实际上就是将一个文件转换成流文件进行读写
							FileUtils.copyFile(fileTest, saveFile);
							user.setUserPhoto("faceimages/" + fileTestFileName);
						} catch (IOException e) {
							msg = "图片上传失败";
							return "imgErro";
						}
					}
				}
				if (type == 0) {
					msg = "上传的图片类型错误";
					return "imgErro";
				}
			}
		}
		if (fileTest1 != null) {
			if (fileTest1.length() > 2097152) {
				msg = "图片未上传或者图片大小超出了2M";
				return "imgErro";
			} else {

				for (String s : str) {
					if (fileTest1FileName.endsWith(s)) {
						type = 1;
						String realPath = ServletActionContext
								.getServletContext().getRealPath("/faceimages");// 实际路径
						// String realPath ="d:/upload/faceimages";
						System.out.println(realPath);
						fileTest1FileName = Tools.getRandomFileName() + s;
						File saveFile = new File(new File(realPath),
								fileTest1FileName); // 在该实际路径下实例化一个文件
						// 判断父目录是否存在
						if (!saveFile.getParentFile().exists()) {
							saveFile.getParentFile().mkdirs();
						}
						try {
							// 执行文件上传
							// FileUtils 类名 org.apache.commons.io.FileUtils;
							// 是commons-io包中的，commons-fileupload 必须依赖
							// commons-io包实现文件上次，实际上就是将一个文件转换成流文件进行读写
							FileUtils.copyFile(fileTest1, saveFile);
							user.setUserQr("faceimages/" + fileTest1FileName);
						} catch (IOException e) {
							msg = "图片上传失败";
							return "imgErro";
						}
					}
				}
				if (type == 0) {
					msg = "上传的图片类型错误";
					return "imgErro";
				}
			}
		}
		// msg = "图片上传成功";

		if (user.getUserPassword() == null) {
			msg = "密码不能为空！";
			return "imgErro";
		} else {
			if (!userPassword.trim().equals(user.getUserPassword().trim())) {
				msg = "两次密码输入不一致！";
				return "imgErro";
			} else {
				user.setUserPassword(userPassword);
			}
		}

		Date date = new Date();
		SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
		String dateString = formatter.format(date);
		user.setRegTime(dateString);
		user.setRecommendationCode(showSmsCode() + "");

		int i = userService.addUser(user);

		return queryAllUserList();

	}

	/**
	 * 批量删除会员
	 * 
	 * @return
	 */
	public String deleteAllUser() {
		int i = userService.deleteUser(num);
		if (i > 0) {
			msg = "删除成功！";
		} else {
			msg = "删除失败！";
		}
		agentId = agentId;
		return queryAllUserList();
	}

	/**
	 * 删除会员
	 * 
	 * @return
	 */
	public String deleteUser() {
		int i = userService.deleteUser1(user.getId());
		if (i > 0) {
			msg = "删除成功！";
		} else {
			msg = "删除失败！";
		}
		return queryAllUserList();
	}

	/**
	 * 修改会员页面
	 * 
	 * @return
	 */
	public String updateUserPage() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		agent = agentService.queryAgentInfo(agentId);
		user = userService.queryUserInfo(user);
		request.setAttribute("user", user);
		request.setAttribute("agent", agent);
		return "updateUserPage";
	}

	/**
	 * 会员详情
	 * 
	 * @return
	 */
	public String queryUserInfo() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		HttpSession session = request.getSession();
		user = userService.queryUserInfo(user);
		request.setAttribute("user", user);
		return "queryUserInfo";
	}

	public String myQRCode() {
		/*
		 * request = ServletActionContext.getRequest(); response =
		 * ServletActionContext.getResponse(); User
		 * user=userService.queryMoneyOfUser(openId);
		 * request.setAttribute("user", user);
		 */

		return "shareCode";
	}

	/**
	 * 注册
	 * 
	 * @return
	 * @throws Exception
	 */
	public String addUser() throws Exception {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();

		User user1 = userService.queryMoneyOfUser(user.getWeChatId());
		User user2 = userService.queryUserSadff(user1.getRecomCode());
		if (user2 != null) {
			if (user2.getUserLevel() == 3) {
				user1.setSadffId(user2.getId());
			} else {
				user1.setSadffId(user2.getSadffId());
			}
			if (user2.getAgentsId() != null) {
				user1.setAgentsId(user2.getAgentsId());
			}
			if (user2.getPartnerId() != null) {
				user1.setPartnerId(user2.getPartnerId());
			}
		}
		user1.setMobile(user.getMobile());
		user1.setUserPassword(user.getUserPassword());
		if (!user.getProvince().equals("省")) {
			user1.setProvince(user.getProvince());
		} else {
			user1.setProvince("全国");
		}
		user1.setUsername(user.getUsername());
		if (!user.getCity().equals("市")) {
			user1.setCity(user.getCity());
		} else {
			user1.setCity("全国");
		}
		if (!user.getArea().equals("区")) {
			user1.setArea(user.getArea());
		} else {
			user1.setArea("全国");
		}
		user1.setUserLevel(1);
		userService.updateUser(user1);

		/*
		 * String
		 * thisa="D:/Program Files/Java/tomcat8.0.36/webapps/FenXiao/uploads";
		 * String text ="http://weixin.qq.com/r/Mzv-57LEse-OrfaE924h"; String
		 * fileName=QRCodeUtil.encode(text, null, thisa, true);
		 * request.setAttribute("imageName",fileName);
		 */
		return "myQRCode";
	}

	public String weixinLogin() throws Exception {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
//		request.setAttribute("userid1", userid1);
		HttpSession session1 = request.getSession();
		   
		
//		      Object user2 = session1.getAttribute("user");
//		      if(user2!=null){
//		    	  
//		      }
		User user1 = null;
		if(user!=null){
		      User user2 = new User();
				String UserPassword = user.getUserPassword();
				String modil = user.getMobile();
				user2.setUserPassword(EncoderByMd5(UserPassword));
				user2.setMobile(modil);
				user1 = userService.weixinLogin(user2);
				
		}
		if (user1 == null) {
			User user3 = new User();
			String UserPassword = user.getUserPassword();
			String modil = user.getMobile();
			user3.setUserPassword(UserPassword);
			user3.setMobile(modil);
			 user1 = userService.weixinLogin(user3);	
		}
		if(user1==null){
			
			msg = "账号输入错误";
			request.setAttribute("msg", msg);
			return "weixinLogin";
		}else {
			Long userid1 = user1.getId();
			session1.setAttribute("user", userid1);
			HttpServletResponse response = ServletActionContext.getResponse();
		    Cookie cokinuserid = new Cookie("userid",String.valueOf(userid1));
		    cokinuserid.setMaxAge(60*10080);
		    response.addCookie(cokinuserid);
			openId = user1.getWeChatId();
			//完成任务
			 Pager pagelist = taskService.queryTaskwc(user1,20, page, search);
			  List<Task> pageli = pagelist.getList();
			  //点亮
			  Pager pagedl = taskService.queryTaskdl(user1, 20, page, search);
			List<Task> pagedls = pagedl.getList();
			 int toal = pagedl.getTotalPage();
			 //总页数
			 int Total = pagelist.getTotalPage();
			List<Task> list = taskService.getTaskAll(user1, null, null);
			int a = 0;
			int b = 0;
			for (int i = 0; i < list.size(); i++) {
				// String strDate = list.get(i).getTaskEndTime();
				SimpleDateFormat sdf = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				// Date date = sdf.parse(strDate);
				if (sdf.parse(list.get(i).getTaskEndTime()).getTime() > new Date()
						.getTime() && list.get(i).getTaskRemainderNumber() > 0 && new Date().getTime()>=sdf.parse(list.get(i).getTaskBeginTime()).getTime()) {
					a += 1;
				} else if (sdf.parse(list.get(i).getTaskEndTime()).getTime() < new Date()
						.getTime() || list.get(i).getTaskRemainderNumber() == 0) {
					b += 1;
				}
			}
			 cishu cishu = cishuService.queryAll();
		      if(cishu.getLioulang()!=null&&cishu.getLioulang()!=0){
		    	  cishu.setLioulang(cishu.getLioulang()+1);
		      }else {
		    	  cishu.setLioulang(1);
			}
		        int i = cishuService.updateliou(cishu);
			    cishu cishu1 = cishuService.queryAll();
			    request.setAttribute("cishu1", cishu1);
			request.setAttribute("a", a);
			request.setAttribute("b", b);
			request.setAttribute("list", list);
			request.setAttribute("openId", openId);
			request.setAttribute("user", user1);
			request.setAttribute("pageli", pageli);
			request.setAttribute("Total", Total);
			request.setAttribute("pagedls", pagedls);
			request.setAttribute("toal", toal);
			request.setAttribute("page", page);
			
			return "index";
		}
	}
//首页
	public String homepage() throws ParseException {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		HttpSession session1 = request.getSession();
//		String openId = request.getParameter("openId");
		 Long  user1 = (Long) session1.getAttribute("user");
			User user = userService.queryuserById(user1);
		 Pager pagelist = taskService.queryTaskwc(user,20, page, search);
		  List<Task> pageli = pagelist.getList();
		  //点亮
			Pager pagedl = taskService.queryTaskdl(user, 20, page, search);
				List<Task> pagedls = pagedl.getList();
				 int toal = pagedl.getTotalPage();
		List<Task> list = taskService.getTaskAll(user, null, null);
		int Total = pagelist.getTotalPage();
		int a = 0;
		int b = 0;
		for (int i = 0; i < list.size(); i++) {
			// String strDate = list.get(i).getTaskEndTime();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			// Date date = sdf.parse(strDate);
			if (sdf.parse(list.get(i).getTaskEndTime()).getTime() > new Date()
					.getTime() && list.get(i).getTaskRemainderNumber() > 0 && new Date().getTime()>=sdf.parse(list.get(i).getTaskBeginTime()).getTime()) {
				a += 1;
			} else if (sdf.parse(list.get(i).getTaskEndTime()).getTime() < new Date()
					.getTime() || list.get(i).getTaskRemainderNumber() == 0) {
				b += 1;
			}
		}
		   cishu cishu = cishuService.queryAll();
		      if(cishu.getLioulang()!=null&&cishu.getLioulang()!=0){
		    	  cishu.setLioulang(cishu.getLioulang()+1);
		      }else {
		    	  cishu.setLioulang(1);
			}
		  int i = cishuService.updateliou(cishu);
		  cishu cishu1 = cishuService.queryAll();
		request.setAttribute("cishu1", cishu1);
		request.setAttribute("a", a);
		request.setAttribute("b", b);
		request.setAttribute("list", list);
		request.setAttribute("pagedls", pagedls);
		request.setAttribute("toal", toal);
		request.setAttribute("openId", user.getWeChatId());
		request.setAttribute("pageli", pageli);
		request.setAttribute("Total", Total);
		request.setAttribute("page", page);
		
		return "index";

	}

	// 查询手机号
	public String checkOwnMobile() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		dataMap = new HashMap<String, Object>();
		String mobile = request.getParameter("mobile");
//		String mobile = user.getMobile();
		User user = userService.checkMobile(mobile);
		String openId = request.getParameter("openId");
		if (user == null) {
			dataMap.put("code", 0);
		} else {
			
				dataMap.put("code", 1);
			
		}

		return "dataMap";
	}
	//进入提现密码
	public String queryBankCardOfTheUser() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		String userId = request.getParameter("userId");
		User user = userService.queryuserById(Long.parseLong(userId));
		Bankcard bankcard = cardService.queryBankcardOfUser(Long
				.parseLong(userId));
		if (bankcard == null) {
			request.setAttribute("userId", userId);
			request.setAttribute("openId", user.getWeChatId());
			return "bindingBankcard";
		} else {
			String modil = bankcard.getCardMobile();
			String lastmodile = modil.substring(0,3)+"****"+modil.substring(7,modil.length());
				request.setAttribute("lastmodile", lastmodile);
				request.setAttribute("modil", modil);
			request.setAttribute("openId", user.getWeChatId());
			request.setAttribute("user", user);
			return "tradePasswordSetUp";
		}
	}

	public String bindingBankcardStep2() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		String userId = request.getParameter("userId");
		User user = userService.queryuserById(Long.parseLong(userId));
		String modil = user.getMobile();
		String lastFour = modil.substring(0,3)+"****"+modil.substring(7,modil.length());
			request.setAttribute("lastFour", lastFour);
			request.setAttribute("modil", modil);
		request.setAttribute("userId", userId);
		request.setAttribute("openId", user.getWeChatId());
		return "bindingBankcardStep2";
	}

	public String moneyToCashSetUp() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		String userId = request.getParameter("userId");
		User user = userService.queryuserById(Long.parseLong(userId));
		Bankcard bankcard = cardService.queryBankcardOfUser(Long
				.parseLong(userId));
		if (bankcard == null) {
			request.setAttribute("userId", userId);
			request.setAttribute("openId", user.getWeChatId());
			return "bindingBankcard";
		} else {
			request.setAttribute("bankcard", bankcard);
			String cardCode = bankcard.getCardCode();
			String lastFour = cardCode.substring(cardCode.length() - 4,
					cardCode.length());
			request.setAttribute("lastFour", lastFour);
			request.setAttribute("openId", user.getWeChatId());
			return "bindingBankcardStep3";
		}
	}
//我的团队
	public String myTeam() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		 HttpSession session1 = request.getSession();
//		String openId = request.getParameter("openId");
		 Long  user1 = (Long) session1.getAttribute("user");
			 
		Integer userLevel = null;
		String search = null;
		search = request.getParameter("search");
		String userLevel1 = request.getParameter("userLevel");
		if (userLevel1 != null) {
			userLevel = Integer.parseInt(userLevel1);
		}
		if (userLevel != null) {
			request.setAttribute("userLevel", userLevel);
		}
	//	直属团队
		User user = userService.queryuserById(user1);
		 Pager pageuser = userService.queryZhishu(10, page, search, user);
		 int Total = pageuser.getTotalPage();
		 List<User> pageuser1 = pageuser.getList();
		 
		List<User> list = userService.queryTeamOfTheUser(user, userLevel,
				search);
		int a = 0;
		int b = 0;
//		Agent agent1 =null;
//		Agent agent2=null;
//		int c = 0;
		int d = 0;
		for (int i = 0; i < list.size(); i++) {

			if (list.get(i).getUserLevel() != 2) {
				a += 1;
			} else if (list.get(i).getUserLevel() == 2) {
				b += 1;
			}
		}
		//查询全部成员
		   
		   Pager pagequanbu = userService.queryQuanbu(10, page, search, user);
		     int total = pagequanbu.getTotalPage();
		     List<User> pageuserlist = pagequanbu.getList();

	    		
	    		 List<User> user2 = userService.queryGetAll(user1);
	    		 if(user2.size()!=0&&user2!=null){
	 		  		d=user2.size();
	    		 }
		request.setAttribute("pageuserlist", pageuserlist);
		request.setAttribute("user", user);
		request.setAttribute("a", a);
		request.setAttribute("b", b);
//		request.setAttribute("c", c);
		request.setAttribute("d", d);
		request.setAttribute("size", list.size());
//		request.setAttribute("list", list);
		request.setAttribute("Total", Total);
		request.setAttribute("total", total);
		request.setAttribute("page", page);
		request.setAttribute("pageuser1", pageuser1);
		request.setAttribute("openId", user.getWeChatId());
		request.setAttribute("search", search);

		return "myTeam";
	}

	public String personalData() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		User user = userService.queryuserById(Long.parseLong(request
				.getParameter("userId")));
		request.setAttribute("user", user);
		request.setAttribute("openId", user.getWeChatId());
		return "index_personal";
	}

	public String getSMSCheckCode() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		dataMap = new HashMap<String, Object>();
		HashMap<String, Object> result = null;
		CCPRestSDK restAPI = new CCPRestSDK();
		String mobile = request.getParameter("mobile");
		/*
		 * String userId=request.getParameter("userId"); User
		 * user=userService.queryuserById(Long.parseLong(userId));
		 */
		restAPI.init("app.cloopen.com", "8883");
		// 初始化服务器地址和端口，生产环境配置成app.cloopen.com，端口是8883.
		restAPI.setAccount("8a48b5514a61a814014a7faa434e11bb",
				"4aeffdba4df3435aa816609728dd5052");
		// 初始化主账号名称和主账号令牌，登陆云通讯网站后，可在"控制台-应用"中看到开发者主账号ACCOUNT SID和
		// 主账号令牌AUTH TOKEN。
		restAPI.setAppId("aaf98f894a70a61d014a7fe71da8099d");
		// 初始化应用ID，如果是在沙盒环境开发，请配置"控制台-应用-测试DEMO"中的APPID。
		// 如切换到生产环境，请使用自己创建应用的APPID
		String checkCode = getSix();
		System.out.println(checkCode);
		dataMap.put("code", checkCode);
		result = restAPI.sendTemplateSMS(mobile, "111684",
				new String[] { checkCode });
		System.out.println("SDKTestGetSubAccounts result=" + result);
		if ("000000".equals(result.get("statusCode"))) {
			// 正常返回输出data包体信息（map）
			HashMap<String, Object> data = (HashMap<String, Object>) result
					.get("data");
			Set<String> keySet = data.keySet();
			for (String key : keySet) {
				Object object = data.get(key);
				System.out.println(key + " = " + object);
				dataMap.put("codeT", 1);
			}
		} else {
			// 异常返回输出错误码和错误信息
			System.out.println("错误码=" + result.get("statusCode") + " 错误信息= "
					+ result.get("statusMsg"));
			dataMap.put("codeT", 0);
			dataMap.put("msg", result.get("statusMsg"));
		}
		response.setHeader("Access-Control-Allow-Origin", "*");
		return "dataMap";
	}

	public String getSix() {
		Random rad = new Random();
		String result = rad.nextInt(1000000) + "";
		if (result.length() != 6) {
			return getSix();
		}
		return result;
	}

	public String forgetPassword() {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		String openId = request.getParameter("openId");
		User user = userService.queryMoneyOfUser(openId);
		String modil = user.getMobile();
		String lastmodile = modil.substring(0,3)+"****"+modil.substring(7,modil.length());
		request.setAttribute("lastmodile", lastmodile);
		request.setAttribute("modil", modil);
		request.setAttribute("user", user);
		request.setAttribute("openId", openId);
		return "forgetPassword";
	}

	public String resetPasword() throws NumberFormatException, Exception {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		String userId = request.getParameter("userId");
		String password = request.getParameter("password");
		userService.resetPassword(Long.parseLong(userId), EncoderByMd5(password));
		 cardService.resetPassword(Long.parseLong(userId), EncoderByMd5(password));
		User user = userService.queryuserById(Long.parseLong(userId));
		request.setAttribute("user", user);
		request.setAttribute("openId", user.getWeChatId());
		return "money";
	}

	public String resetPasswpord1() throws NumberFormatException, Exception {
		request = ServletActionContext.getRequest();
		response = ServletActionContext.getResponse();
		String userId = request.getParameter("userId");
		String password = request.getParameter("password");
		userService.resetPassword(Long.parseLong(userId), EncoderByMd5(password));
	    cardService.resetPassword(Long.parseLong(userId), EncoderByMd5(password));
		User user = userService.queryuserById(Long.parseLong(userId));
		request.setAttribute("user", user);
		request.setAttribute("openId", user.getWeChatId());
		return "money";
	}

	// 随机生成 6 位数推荐码
	public int showSmsCode() {

		return (int) ((Math.random() * 9 + 1) * 100000);
	}

	public AgentService getAgentService() {
		return agentService;

	}

	public void setAgentService(AgentService agentService) {
		this.agentService = agentService;
	}

	public long getAgentId() {
		return agentId;
	}

	public void setAgentId(long agentId) {
		this.agentId = agentId;
	}

	public String getUserPassword() {
		return userPassword;
	}

	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}

	public File getFileTest() {
		return fileTest;
	}

	public void setFileTest(File fileTest) {
		this.fileTest = fileTest;
	}

	public String getFileTestFileName() {
		return fileTestFileName;
	}

	public void setFileTestFileName(String fileTestFileName) {
		this.fileTestFileName = fileTestFileName;
	}

	public File getFileTest1() {
		return fileTest1;
	}

	public void setFileTest1(File fileTest1) {
		this.fileTest1 = fileTest1;
	}

	public String getFileTest1FileName() {
		return fileTest1FileName;
	}

	public void setFileTest1FileName(String fileTest1FileName) {
		this.fileTest1FileName = fileTest1FileName;
	}

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}

	public HttpServletRequest getRequest() {
		return request;
	}

	public void setRequest(HttpServletRequest request) {
		this.request = request;
	}

	public HttpServletResponse getResponse() {
		return response;
	}

	public void setResponse(HttpServletResponse response) {
		this.response = response;
	}

	public HttpSession getSession() {
		return session;
	}

	public void setSession(HttpSession session) {
		this.session = session;
	}

	public Agent getAgent() {
		return agent;
	}

	public void setAgent(Agent agent) {
		this.agent = agent;
	}

	public int getPage() {
		return page;
	}

	public void setPage(int page) {
		this.page = page;
	}

	public Pager getPageBean() {
		return pageBean;
	}

	public void setPageBean(Pager pageBean) {
		this.pageBean = pageBean;
	}

	public List<User> getUserList() {
		return userList;
	}

	public void setUserList(List<User> userList) {
		this.userList = userList;
	}

	public String getSearch() {
		return search;
	}

	public void setSearch(String search) {
		this.search = search;
	}

	public String getNum() {
		return num;
	}

	public void setNum(String num) {
		this.num = num;
	}

	public String getMsg() {
		return msg;
	}

	public void setMsg(String msg) {
		this.msg = msg;
	}

	public TaskService getTaskService() {
		return taskService;
	}

	public void setTaskService(TaskService taskService) {
		this.taskService = taskService;
	}

	public CardService getCardService() {
		return cardService;
	}

	public void setCardService(CardService cardService) {
		this.cardService = cardService;
	}

	public Map<String, Object> getDataMap() {
		return dataMap;
	}

	public void setDataMap(Map<String, Object> dataMap) {
		this.dataMap = dataMap;
	}

	public PresentService getPresentService() {
		return presentService;
	}

	public void setPresentService(PresentService presentService) {
		this.presentService = presentService;
	}

	public String getOpenId() {
		return openId;
	}

	public void setOpenId(String openId) {
		this.openId = openId;
	}

}
